var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
//日志
var logger = require('morgan');
//引入cookie
var cookieParser = require('cookie-parser');
//引入session
let session=require('express-session')
var bodyParser = require('body-parser');

var register=require('./routes/register');
var login=require('./routes/login');
var pwd=require('./routes/pwd');
var index = require('./routes/index');
var users = require('./routes/users');
var bookInfo=require('./routes/bookInfo')

var app = express();

// view engine setup设置视图
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');


//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//中间件
app.use(session({
  secret: "xzsagjasoigjasoi",
  resave:true,//强制保存session
  cookie:{
    maxAge:7*24*60*60*1000,//设置session的有效期为1周
  },
  saveUninitialized:true//是否保存初始化的session
}))
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//extended: false：表示使用系统模块querystring来处理，也是官方推荐的
//extended: true：表示使用第三方模块qs来处理
app.use(cookieParser('secret'));
app.use('/loginOut',function(req,res){
	//注销session
	req.session.destroy(function(err){
		res.redirect('/login')
	});
});
//express内置中间件  处理静态资源
app.use(express.static(path.join(__dirname, 'public')));


//路由匹配
app.use('/', index);
app.use('/register',register);
app.use('/login',login);
app.use('/pwd',pwd);
app.use('/book',bookInfo)
app.use('/users', users);

// catch 404 and forward to error handler
//设置404页面中间件
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  res.render('404.ejs')
});

// error handler处理错误中间件
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
